package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;
import android.app.Dialog;
import android.support.annotation.Nullable;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.allenliu.versionchecklib.core.http.HttpParams;
import com.allenliu.versionchecklib.core.http.HttpRequestMethod;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.UpdateData;
import com.eduhzy.ttw.commonsdk.http.CommonApi;
import com.eduhzy.ttw.teacher.R;
import com.eduhzy.ttw.teacher.mvp.contract.SetUpContract;
import com.eduhzy.ttw.teacher.mvp.ui.activity.SetUpActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class SetUpPresenter extends BasePresenter<SetUpContract.Model, SetUpContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    Gson mGson;

    @Inject
    public SetUpPresenter(SetUpContract.Model model, SetUpContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void updateByPassword(String pwd, String pwd2) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("new_password", pwd);
        map.put("rep_password", pwd2);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.updateByPassword(map).subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {

                    @Override
                    public void onNext(CommonData<Map> mapCommonData) {
                        if (mapCommonData.isResult()) {
                            RxUtil.showTipDialog(ActivityUtils.getTopActivity(), QMUITipDialog.Builder.ICON_TYPE_SUCCESS, mapCommonData.getMessage(), 1500);
                            SPUtils.getInstance().put(Constants.PASSWORD, "");
                            SPUtils.getInstance().put(Constants.USERID, "");
                            SPUtils.getInstance().put(Constants.TOKEN, "");
                            ARouter.getInstance().build(RouterHub.APP_LOGINACTIVITY).withBoolean(AppManager.IS_NOT_ADD_ACTIVITY_LIST, true).navigation();
                            ArmsUtils.killAll();
                        }
                    }
                });
    }

    public void getAppUpdate() {

        HttpParams requestParams = new HttpParams();
        requestParams.put("packageName", mRootView.getActivity().getPackageName());
        requestParams.put("versionCode", AppUtils.getAppVersionCode());
        DownloadBuilder builder = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestMethod(HttpRequestMethod.POSTJSON)
                .setRequestUrl(CommonApi.APP_DOMAIN + CommonApi.APP_UPDATE)
                .setRequestParams(requestParams)
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(String result) {
                        CommonData<UpdateData> commonData = mGson.fromJson(result, new TypeToken<CommonData<UpdateData>>() {
                        }.getType());
                        if (commonData.isResult()) {
                            UpdateData data = commonData.getData();

                            return UIData.create().setDownloadUrl(data.getFilePath()).setContent(data.getUpdateDesc());
                        } else {
                            if (mRootView.getActivity() instanceof SetUpActivity) {
                                mRootView.showMessage(commonData.getMessage());
                            }
                            return null;
                        }
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                });
        builder.setForceRedownload(true);
        builder.setCustomVersionDialogListener(createCustomDialogTwo());
        builder.executeMission(mRootView.getActivity());
    }

    private CustomVersionDialogListener createCustomDialogTwo() {
        return (context, versionBundle) -> {
            Dialog baseDialog = new Dialog(context, R.style.BaseDialog);
            baseDialog.setCancelable(false);
            baseDialog.setContentView(R.layout.custom_dialog_two_layout);
            TextView textView = baseDialog.findViewById(R.id.tv_msg);
            textView.setText(versionBundle.getContent());
            baseDialog.setCanceledOnTouchOutside(false);
            return baseDialog;
        };
    }
}
